<template>
  <div class="functionalAuthority">
    <div class="topBox" :class="{ hid: !menuData }">
      <div class="treeMenuRight" v-if="menuData && data2.length">
        <div class="menuCurr" v-if="childFlag">
          <p>
            <span>组织ID：</span>
            <span>{{ menuData.id }}</span>
          </p>
          <p>
            <span>上级组织ID：</span>
            <span>{{ menuData.parentId == 0 ? '没有上级菜单' : menuData.parentId }}</span>
          </p>
          <p>
            <span>组织级别：</span>
            <span>{{ menuData.level | levelFilters }}</span>
          </p>
          <p>
            <span>组织名称：</span>
            <span><Input v-model="menuData.title" placeholder="请输入组织名字" style="width: 220px" /></span>
          </p>
          <div class="menuBtn">
            <Button type="success" @click="permissionUpdate" v-preventReClick>保存</Button>
            <Button type="success" @click="permissionBind" v-preventReClick>绑定</Button>
            <Button type="warning" @click="permissionDelete">删除</Button>
            <Button type="primary" @click="createChildMenu" v-if="createText != ''">{{ createText }}</Button>
          </div>
        </div>
        <div class="menuCurr" v-if="!childFlag">
          <p>
            <span>上级组织ID：</span>
            <span>{{ menuData.id }}</span>
          </p>
          <p>
            <span>组织名称：</span>
            <span><Input v-model="createMenuName" placeholder="请输入组织名字" style="width: 220px" /></span>
          </p>
          <div class="menuBtn">
            <Button type="text" @click="createMenuNameCancel">取消</Button>
            <Button type="success" @click="permissionSave" v-preventReClick>保存</Button>
          </div>
        </div>
      </div>
    </div>
    <Button type="primary" @click="scopeDeploy" class="scope_deploy">人员异动范围配置</Button>
    <div class="treeMenu" ref="TableHeight" :style="{ height: onresizeHeight + 'px' }">
      <Row>
        <Col :xs="2" :sm="4" :md="6" :lg="8" class="treeMenuLeft">
          <div class="tit">业务组织架构</div>
          <Tree :data="data1" @on-select-change="treeSelChange"></Tree>
        </Col>
        <Col :xs="2" :sm="4" :md="6" :lg="8">
          <div class="tit">OA组织架构</div>
          <Tree
            :data="data2"
            show-checkbox
            check-strictly
            check-directly
            @on-check-change="pcSelChange"></Tree>
        </Col>
      </Row>
    </div>
    <dt-loading :loading="loading" />
  </div>
</template>

<script>
  import jurisdictionMgr from '@/biz/jurisdiction/jurisdiction'
  import organizationManagementMgr from '@/biz/organizationManagement/organizationManagement'
  import userMgr from '@/biz/user'
  export default {
    name: 'functionalAuthority',
    data() {
      return {
        userId: userMgr.info().userId,
        roleId: userMgr.info().role.roleId,
        onresizeHeight: '',
        childFlag: true,
        TabVal: 'name1',
        menuData: '',
        createMenuName: '',
        data1: [],
        data2: [],
        webMenuList: [],
        cannotBind: [],
        createText: '创建事业部',
        loading: false
      }
    },
    directives: {
      preventReClick: {
        inserted(el, binding) {
          el.addEventListener('click', () => {
            if (!el.disabled) {
              el.disabled = true
              setTimeout(() => {
                el.disabled = false
              }, binding.value || 3000)
            }
          })
        }
      }
    },
    mounted() {
      window.onresize = () => {
        return (() => {
          setTimeout(() => {
            this.onresizeHeight = window.innerHeight - this.$refs.TableHeight.offsetTop - 50
          }, 10)
        })()
      }
    },
    filters: {
      levelFilters(value) {
        let set = {
          0: '同策',
          1: '事业部',
          2: '分公司',
          3: '事业处'
        }
        return set.hasOwnProperty(value) ? set[value] : value
      }
    },
    methods: {
      scopeDeploy() {
        this.$router.push({
          path: 'scopeDeployPage'
        })
      },
      pcSelChange(val) {
        this.webMenuList = []

        val.forEach((item) => {
          this.webMenuList.push(item.departmentId)
        })
      },
      treeSelChange(val) {
        if (val.length != 0) {
          let vv = this.$tool.deepClone(val)
          this.childFlag = true
          if (vv && vv.length) {
            this.menuData = vv[0]
          } else {
            this.menuData = ''
          }
          this.createText =
            this.menuData.level == 0
              ? '创建事业部'
              : this.menuData.level == 1
              ? '创建分公司'
              : this.menuData.level == 2
              ? '创建事业处'
              : ''
          this.ergodicId()
        }
      },
      createChildMenu() {
        if (this.menuData.level > 4) {
          this.$Message.warning('菜单最大为5级。')
        } else {
          this.childFlag = false
        }
      },
      createMenuNameCancel() {
        this.childFlag = true
        this.createMenuName = ''
      },
      recursion1(data) {
        data.forEach((item) => {
          item.expand = 'true'
          item.title = item.name
          if (item.children && item.children.length) {
            this.recursion1(item.children)
            item.disabled = true
          }
        })
      },
      // OA架构
      getOaList() {
        let params = {
          userId: this.userId,
          roleId: this.roleId
        }
        return organizationManagementMgr.getOA(params).then((res) => {
          this.recursion1(res)
          this.data2 = res
          return res
        })
      },

      // 业务架构
      getBusinessList() {
        return organizationManagementMgr.getOrg().then((res) => {
          this.recursion(res)
          this.data1 = res
          return res
        })
      },
      recursion(data) {
        data.forEach((item) => {
          item.expand = 'true'
          item.title = item.orgName
          if (item.children && item.children.length) {
            this.recursion(item.children)
          }
        })
      },
      //建权限
      permissionSave() {
        let params = {
          parentId: this.menuData.id, //上级菜单id
          orgName: this.createMenuName //菜单名称
        }
        organizationManagementMgr.addNode(params).then((res) => {
          this.$Message.success('菜单创建成功')
          this.menuData = ''
          this.createMenuNameCancel()
          this.getBusinessList()
          this.getOaList()
          this.ergodicId()
        })
      },
      permissionBind() {
        this.loading = true
        let params = {
          id: this.menuData.id, //#权限id
          oaOrgIds: this.webMenuList
        }
        organizationManagementMgr
          .bindOrg(params)
          .then((res) => {
            this.loading = false
            this.$Message.success('组织关联成功')
          })
          .catch((err) => {
            this.loading = false
          })
      },
      // 修改权限
      permissionUpdate() {
        let params = {
          id: this.menuData.id,
          orgName: this.menuData.title //菜单名称
        }
        organizationManagementMgr.editNode(params).then((res) => {
          this.getBusinessList()
          this.menuData = ''
          this.ergodicId()
          this.$Message.success('组织编辑成功')
        })
      },
      permissionDelete() {
        this.$Modal.confirm({
          title: '删除菜单',
          content: `<p>确定删除菜单“${this.menuData.title}”？</p>`,
          onOk: () => {
            let params = {
              id: this.menuData.id
            }
            organizationManagementMgr.delNode(params).then((res) => {
              this.$Message.success('菜单删除成功')
              this.createMenuNameCancel()
              this.getBusinessList()
              this.menuData = ''
            })
          }
        })
      },

      getFunctionMenuList2() {
        let params1 = {
          menuItem: '2'
        }
        jurisdictionMgr.functionMenuList2(params1).then((res) => {
          this.data3 = res
        })
      },

      // 递归遍历勾选上的id合集
      ergodicId() {
        this.recursionTree(this.data2, [])
        if (!this.menuData.id) return false
        this.loading = true
        let params = {
          id: this.menuData.id
        }
        organizationManagementMgr.getOrgBindInfo(params).then((res) => {
          this.loading = false
          this.webMenuList = this.$tool.deepClone(res.hadBind)
          this.cannotBind = this.$tool.deepClone(res.cannotBind)
          this.recursionTree(this.data2, this.webMenuList)
          this.recursionTree1(this.data2, this.cannotBind)
        })
      },
      // 不能再次绑定
      recursionTree1(arr, ids) {
        if (ids) {
          arr.forEach((item) => {
            if (item.children && item.children.length > 0) {
              this.recursionTree1(item.children, ids)
            } else {
              if (ids.includes(item.departmentId)) {
                this.$set(item, 'disabled', true)
              } else {
                this.$set(item, 'disabled', false)
              }
            }
          })
        }
      },

      // 递归菜单树
      recursionTree(arr, ids) {
        if (ids) {
          arr.forEach((item) => {
            if (item.children && item.children.length > 0) {
              this.recursionTree(item.children, ids)
            } else {
              if (ids.includes(item.departmentId)) {
                this.$set(item, 'checked', true)
              } else {
                this.$set(item, 'checked', false)
              }
            }
          })
        } else {
          arr.forEach((item) => {
            this.$set(item, 'checked', false)
            if (item.children && item.children.length > 0) {
              this.recursionTree(item.children)
            }
          })
        }
      }
    },
    created() {
      this.$nextTick(function () {
        this.onresizeHeight = window.innerHeight - this.$refs.TableHeight.offsetTop - 50
      })
      this.loading = true
      Promise.all([this.getBusinessList(), this.getOaList()])
        .then((res) => {
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    }
  }
</script>
<style lang="scss" scoped>
  .functionalAuthority {
    padding: 20px;
    position: relative;

    .scope_deploy {
      position: absolute;
      top: 20px;
      right: 20px;
    }

    .topBox {
      height: 50px;

      .treeMenuRight {
        line-height: 32px;

        .menuCurr {
          display: flex;
          flex-direction: row;

          p {
            margin-right: 15px;

            span:first-child {
              display: inline-block;
              text-align: right;
            }
          }

          .menuBtn {
            > * {
              margin-left: 10px;
            }
          }
        }
      }
    }

    .topBox.hid {
      visibility: hidden;
    }

    .treeMenuLeft {
      position: relative;
    }
  }

  ::v-deep .ivu-row {
    height: 100%;
    overflow: hidden;

    .ivu-col {
      overflow-y: auto;
      height: 100%;
    }
  }

  .tit {
    font-size: 16px;
    color: #333;
    font-weight: bold;
    padding-left: 15px;
  }
</style>
